function Test-SQLConnection
{    
    Param
    (
        [Parameter(Mandatory=$true, Position=0)][System.Data.SqlClient.SqlCredential] $SourceCredentials,
        [Parameter(Mandatory=$true, Position=1)][string] $SourceServerName,
        [Parameter(Mandatory=$true, Position=2)][string] $SourceDatabaseName,
        [Parameter(Mandatory=$false, Position=3)][string] $query
    )
    # Make sure there is only one consecutive backslash
    $SourceServerName = $SourceServerName -replace '\\+', '\'
    try
    {
        # Construct connection string.
        $ConnectionString = "Data Source=$SourceServerName;database=$SourceDatabaseName;"
        # Create sql connection object.
        [System.Data.SqlClient.SqlConnection]$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
        # Set the connection string.
        $sqlConnection.ConnectionString = $ConnectionString
        # Set the credential.
        $sqlConnection.Credential = $SourceCredentials
        # Try to open a connection.
        $sqlConnection.Open();

        $resultsFromQuery = $null
        if ($query) {
            try {
                [System.Data.SqlClient.SqlCommand]$command = New-Object System.Data.SqlClient.SqlCommand($query, $sqlConnection)
                [System.Data.SqlClient.SqlDataAdapter]$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
                [System.Data.DataSet]$dataset = New-Object System.Data.DataSet
                $adapter.Fill($dataset) | Out-Null
                $resultsFromQuery = $dataset.Tables
            }
            catch {
                Write-Host 'Query failed...'
            }
        }

        # Close the connection.
        $sqlConnection.Close();
        
        $true;
        if ($resultsFromQuery) {
            return $resultsFromQuery
        }
    }
    catch
    {
        return $false;
    }
}